package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.StatisticsMapper;
import com.sky.service.StatisticsService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class StatisticsServiceImpl implements StatisticsService {

    @Autowired
    private StatisticsMapper statisticsMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计接口
     */
    public TurnoverReportVO turnover(LocalDate begin, LocalDate end) {
//        计算开始时间到结束时间的日期
        List<LocalDate> dateList = countDateList(begin, end);
//        获取处于开始时间到结束时间的营业额数据
//        select SUM(amount) from orders where status =5 and order_time >begin and order_time <end
        ArrayList<Double> turnovers = new ArrayList();
        for (LocalDate localDate : dateList) {
            LocalDateTime MinLocalTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime MaxLocalTime = LocalDateTime.of(localDate, LocalTime.MAX);
            HashMap map = new HashMap();
            map.put("begin",MinLocalTime);
            map.put("end",MaxLocalTime);
            map.put("status", Orders.COMPLETED);
            Double turnover=statisticsMapper.listTurnover(map);
            turnover = turnover == null ? 0.00 : turnover;
            turnovers.add(turnover);
        }
        return new TurnoverReportVO(StringUtils.join(dateList,","),
                StringUtils.join(turnovers,","));
    }

    /**
     * 用户量统计
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO UserReport(LocalDate begin, LocalDate end) {
        //        计算开始时间到结束时间的日期
        List<LocalDate> dateList = countDateList(begin, end);
        ArrayList newUserList = new ArrayList();
        ArrayList totalUserList = new ArrayList();
        for (LocalDate localDate : dateList) {
            LocalDateTime MinLocalTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime MaxLocalTime = LocalDateTime.of(localDate, LocalTime.MAX);
//            select count(id) from orders where create_time <end and create_time> begin
//            新增用户数
            Integer newUserCount=  statisticsMapper.listUser(MinLocalTime,MaxLocalTime);
            newUserList.add(newUserCount);
//            select count(id) from orders where create_time <end
//            总用户数
            Integer totalUseCount=  statisticsMapper.listUser(null,MaxLocalTime);
            totalUserList.add(totalUseCount);
        }
        return UserReportVO
                .builder()
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList( StringUtils.join(totalUserList,","))
                .dateList(StringUtils.join(dateList,","))
                .build();
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO OrderReport(LocalDate begin, LocalDate end) {
        List<LocalDate> DateList = countDateList(begin, end);
//        有效订单数列表
        List<Integer> validOrderCountList = new ArrayList();
//        订单数列表
        List<Integer> orderCountList = new ArrayList();
        for (LocalDate localDate : DateList) {
            LocalDateTime MinLocalTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime MaxLocalTime = LocalDateTime.of(localDate, LocalTime.MAX);
            HashMap map = new HashMap();
//            添加每天订单总数
            map.put("end",MaxLocalTime);
            map.put("begin", MinLocalTime);
            Integer totalOrderCount= statisticsMapper.listOrder(map);
            orderCountList.add(totalOrderCount);
//            添加每天有效订单数
            map.put("status",Orders.COMPLETED);
            Integer validOrderCount= statisticsMapper.listOrder(map);
            validOrderCountList.add(validOrderCount);
        }
//        每天订单总数    
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
//        每天有效订单数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
//        订单完成率为:
        Double orderCompletionRate=0.0;
        if(totalOrderCount!=0){
             orderCompletionRate=validOrderCount.doubleValue()/totalOrderCount;
        }
        return OrderReportVO
                .builder()
                .orderCompletionRate(orderCompletionRate)
                .orderCountList(StringUtils.join(orderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .dateList(StringUtils.join(DateList,","))
                .build();
    }

    //    计算开始时间到结束时间的日期
    private  List<LocalDate> countDateList(LocalDate begin, LocalDate end){
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin= begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }

    /**
     * 销量排行TOP10接口
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO SalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime  = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime  = LocalDateTime.of(end, LocalTime.MAX);
//        根据商品名分组来查询商品的销量(条件:已完成订单与在规定时间内)
        List<GoodsSalesDTO> goods= statisticsMapper.listSales(beginTime,endTime);
//        遍历商品集合,来获取商品名以及销量
        List<String> names = goods.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numbers = goods.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        return SalesTop10ReportVO
                .builder()
                .numberList(StringUtils.join(numbers,","))
                .nameList(StringUtils.join(names,","))
                .build();
    }

    /**
     * 导出Excel报表接口
     */
    public void export(HttpServletResponse response) {
//        1.查询数据库，获取营业数据--查询最近30天的运营数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
//        查询概览数据
        BusinessDataVO businessData = workspaceService.
                getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN),
                LocalDateTime.of(dateEnd, LocalTime.MAX));
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/OperationalDataReportTemplate.xlsx");

//        2.通过POI将数据写入到Excel文件中
        try {
            XSSFWorkbook excel  = new XSSFWorkbook(inputStream);
            XSSFSheet sheet1 = excel.getSheet("Sheet1");
//            获得第2行
            XSSFRow row = sheet1.getRow(1);
            row.getCell(1).setCellValue("时间:"+dateBegin+"至"+dateEnd);
//            获得第4行
            row= sheet1.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
//            获得第5行
            row = sheet1.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());


//          填充近30天中每一天的明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate Begin = LocalDate.now().minusDays(30);
                LocalDate date = Begin.plusDays(i);
                BusinessDataVO detail = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                 row = sheet1.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(detail.getTurnover());
                row.getCell(3).setCellValue(detail.getValidOrderCount());
                row.getCell(4).setCellValue(detail.getOrderCompletionRate());
                row.getCell(5).setCellValue(detail.getUnitPrice());
                row.getCell(6).setCellValue(detail.getNewUsers());

            }


//        3.通过输出流将Excel文件下载到客户端
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            excel.close();
            out.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }


}
